// components/Bigbang/index.js

const { bigbang } = require("../../common/utils");
const computedBehavior = require('miniprogram-computed');//computed 拓展
const watchBehavior = require("miniprogram-watch");
let tempVal = "";


/**
 * Bigbang 分词选择组件
 */
Component({
  behaviors: [computedBehavior,watchBehavior],
  options:{
    addGlobalClass: true,
  },
  /**
   * 组件的属性列表
   */
  properties: {
    text:{
      type:[String,Array],
      value:'',
      observer(nv,ov){
        this.init(nv)
      }
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    words:[],
    all:false,
    boom:false,
    booming:false,
  },
  watch:{
    curText(nv){
      // console.log("值变化",nv)
      this.handleChange(nv)
    }

  },
  computed:{
    //当前选择的文字
    curText(data){
      let  checkedItem = data.words.filter(item=>item.checked);//筛选
      checkedItem= checkedItem.map(item=>item.text);//映射
      let text = checkedItem.reduce((c,p)=>`${c}${p}`,'');//拼接
      return text
    },
     test(data){
        return "异步测试"
    },
  },
  created(){},
  methods: {
    // 初始化
    async init(){
      let {text} =this.data
      
      let words;
      if(Array.isArray(text)){
        words= text;  
      }else{
        words= await bigbang({text});
      }
      words=words.map(item=>({checked:false,text:item}))
      this.setData({words})
    },
    //内容变化
    async handleChange(value){
      if(tempVal === value){return};//不知道为什么 会触发两次 所以两次值一样就过滤掉
      tempVal = value;
      console.log("触发Change",value);
      this.triggerEvent("Change",value);//向父组件触发事件
      
    
    },
    //文字变化
    handleTextChange({detail:{value}}){
      // console.log("文字输入Change",value);
      this.setData({
        curText:value
      })
    },
//全选按钮
    handleChoseAll(){
       let {all,words} = this.data;
       all = !all;
       words= words.map(item=>{
         item.checked = all;
         return item;
       })
       this.setData({words,all})
         
    },
    //词语选择
    handleWordTap({currentTarget:{dataset}}){
      let {index} = dataset;
      let checked = this.data.words[index]['checked'];
      this.setData({
        [`words[${index}].checked`]:!checked 
      })
      // console.log("文字选择",checked,!checked ,index)
    },
    //爆炸（重组后分词 )
    async handleBoom(texts){
      let {boom} = this.data;
      boom=!boom;
      if(boom){
        this.setData({booming:true})
        let text =this.data.words.map(item=>item.text).reduce((c,p)=>`${c}${p}`,'');
        let words = await bigbang({text});
        words=words.map(item=>({checked:false,text:item}))
        this.setData({booming:false,words,boom:true,all:false})
      }else{
        let {text:words} = this.data;
        words=words.map(item=>({checked:false,text:item}))
        this.setData({booming:false,words,boom:false,all:false})
      }
    }
  }
})
